import dbUtils from './util.strotage'
import axios from 'axios'

/**
 * 16进制颜色转换透明度后的16进制颜色值
 * @param {string} color 原始颜色 #FFFFFF
 * @param {number} opacity 颜色透明度 10 20
 * @returns {string} 转换后的颜色值
 */
export const adjustColorOpacity = function (color, opacity) {
    // 移除 # 号（如果有）
    color = color.replace('#', '')

    // 将十六进制颜色值转换为 RGB 值
    const r = parseInt(color.substring(0, 2), 16)
    const g = parseInt(color.substring(2, 4), 16)
    const b = parseInt(color.substring(4, 6), 16)

    // 将透明度转换为 0 到 1 之间的值
    opacity = opacity / 100

    // 计算插值后的颜色值
    const interpolatedR = Math.round((1 - opacity) * 255 + opacity * r)
    const interpolatedG = Math.round((1 - opacity) * 255 + opacity * g)
    const interpolatedB = Math.round((1 - opacity) * 255 + opacity * b)

    // 将插值后的 RGB 值转换回十六进制颜色值
    let result = '#' + (interpolatedR < 16 ? '0' : '') + interpolatedR.toString(16)
    result += (interpolatedG < 16 ? '0' : '') + interpolatedG.toString(16)
    result += (interpolatedB < 16 ? '0' : '') + interpolatedB.toString(16)

    return result
}

/**
 * 判断空对象
 * @param {Object} obj 原始对象
 * @returns {Boolean} 返回true/false
 */
export const isEmptyObject = function (obj) {
    return JSON.stringify(obj) === '{}'
}

/**
 * 替换字符串中间的数字为指定字符
 * @param {string} str 原始字符串
 * @param {string} replaceChar 替换的字符，默认为'*'
 * @param {number} numDigits 保留的数字位数，默认为1
 * @returns {string} 替换后的字符串
 */
export const replaceMiddleDigits = (str, replaceChar = '*', numDigits = 1) => {
    if (str.length < numDigits + 2) {
        return str
    }
    const firstPart = str.substring(0, numDigits)
    const lastPart = str.substring(str.length - numDigits)
    const middlePart = replaceChar.repeat(str.length - numDigits * 2)

    return firstPart + middlePart + lastPart
}

/**
 * 判断本地存储用户的权限信息作对比
 * @param {string} permission 权限标识 ‘sys:demon:list’
 * @returns {Boolean} 返回true/false
 */
export const hasPerms = function (permission) {
    const permissionList = dbUtils.get('perms')
    if (permissionList.includes('*')) return true
    return permissionList.includes(permission)
}

// 全屏
export const openFullscreen = function () {
    const element = document.documentElement

    if (element.requestFullscreen) {
        element.requestFullscreen()
    } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen()
    } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen()
    } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen()
    }
}
// 全屏某个dom
export const openElementFullscreen = function (element) {
    if (element.requestFullscreen) {
        element.requestFullscreen()
    } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen()
    } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen()
    } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen()
    }
}

// 关闭全屏
export const closeFullscreen = function () {
    if (document.exitFullscreen) {
        document.exitFullscreen()
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen()
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen()
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen()
    }
}

//  网速计算
export const unitGBS = val => {
    const TB = 1024 * 1024 * 1024 * 1024
    const GB = 1024 * 1024 * 1024
    const MB = 1024 * 1024
    const KB = 1024

    if (!val) {
        return ''
    }
    if (val >= TB) {
        return `${Math.floor((val / TB) * 8)}Tbps`
    } else if (val >= GB) {
        return `${Math.floor((val / GB) * 8)}Gbps`
    } else if (val >= MB) {
        return `${Math.floor((val / MB) * 8)}Mbps`
    } else {
        return `${Math.floor((val / KB) * 8)}Kbps`
    }
}

//   内存计算
export const printSize = val => {
    const TB = 1024 * 1024 * 1024 * 1024
    const GB = 1024 * 1024 * 1024
    const MB = 1024 * 1024
    const KB = 1024
    if (!val) {
        return 0 + 'bytes'
    }
    if (val >= TB) {
        return `${(val / TB).toFixed(2)}TB`
    } else if (val >= GB) {
        return `${(val / GB).toFixed(2)}GB`
    } else if (val >= MB) {
        return `${(val / MB).toFixed(2)}MB`
    } else if (val >= KB) {
        return `${(val / KB).toFixed(2)}KB`
    } else {
        return `${val}bytes`
    }
}

//  GB内存计算
export const printGBSize = val => {
    const GB = 1024 * 1024 * 1024
    if (!val) {
        return 0
    }

    return `${(val / GB).toFixed(2)}`
}

// 根据value回显label
export function selectDictLabel(datas, value) {
    if (value === undefined) {
        return "";
    }
    var actions = [];
    Object.keys(datas).some((key) => {
        if (datas[key].value == ('' + value)) {
            actions.push(datas[key].label);
            return true;
        }
    })
    if (actions.length === 0) {
        actions.push(value);
    }
    return actions.join('');
}

// 根据参数名获取url参数值
export function getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}

// 计算2个时间的时长
export function dateLong(start, end) {
    if (!start || !end) {
        return
    }
    let startTime = new Date(start.replace(/-/g, "/"))
    let endTime = new Date(end.replace(/-/g, "/"))
    var dataDiff = endTime.getTime() - startTime.getTime()


    if (dataDiff < 0) {
        return
    }
    //天数
    var dayDiff = Math.floor(dataDiff / (24 * 3600 * 1000))
    //小时
    var leave1 = dataDiff % (24 * 3600 * 1000)
    var hours = Math.floor(leave1 / (3600 * 1000))
    //分钟
    var leave2 = leave1 % (3600 * 1000)
    var minutes = Math.floor(leave2 / (60 * 1000))
    //秒数
    var leave3 = leave2 % (60 * 1000)
    var seconds = Math.round(leave3 / 1000)

    let str = ''
    if (dayDiff) {
        str += dayDiff + '天'
    } else if (hours) {
        str += hours + '小时'
    } else if (minutes) {
        str += minutes + '分钟'
    } else if (seconds) {
        str += seconds + '秒'
    }

    return str

}

// 通用导出方法
export function download(url, params, filename) {
    axios({
        url: import.meta.env.VITE_APP_BASE_API + url,//请求的真是地址
        method: 'get',
        params,
        headers: {'gm-session-id': dbUtils.get('token') },
        responseType: 'blob'
    }).then(res => {
        // downloadXls(res,`账单明细.xlsx`)
        var blob = new Blob([res.data], {
            type: "application/vnd.ms-excel;charset=utf-8"
        });//"application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8"表示的是doc类型，Excel可以选择'application/vnd.ms-excel;charset=utf-8';
        var contentDisposition = res.headers["content-disposition"]; //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
        var patt = new RegExp(
            "filename=([^;]+\\.[^\\.;]+);*"
        );
        var result = patt.exec(contentDisposition);
        var filename = result[1];
        var downloadElement = document.createElement("a");
        var href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.style.display = "none";
        downloadElement.href = href;
        downloadElement.download = decodeURI(filename); //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
    })
}

// 根据不同环境加载OSS远程图片
export function handleImg(val) {
    return  `${import.meta.env.VITE_OSS_PATH}/assets/img/${val}`
}